import React from 'react';
import { Select, Form, Button } from 'antd';
import { useDebounceFn } from 'ahooks';
import moment from 'moment';

import { CalendarOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import { PageLoading, TRDefault } from '@/components/index.js';

import { tableHead_3, OPTION_KEY, YearOptions } from '../../helper.js';
import { querypowerGenerationData, useNewServers } from '../../services.js';
import { MonthRatioTable } from '../BaseTable';
import CheckedList from '../CheckedList';
import styles from './index.less';

let isFirst = false;

const MySelect = (props: any) => {
  const { value = [], onChange, options = [] } = props;
  return (
    <>
      <Select
        showSearch={false}
        value={value}
        options={options}
        style={{ width: 216 }}
        placeholder="请选择参考年份"
        mode="multiple"
        maxTagCount={1}
        maxTagTextLength={4}
        onChange={onChange}
        dropdownRender={() =>
          options.length ? (
            <CheckedList options={options} onChange={onChange} value={value} />
          ) : (
            <TRDefault type="emptysm" />
          )
        }
      />
      <CalendarOutlined className={styles.icon_calendar} />
    </>
  );
};

const MonthRatio = ({ stations, selectData, year }: any) => {
  const [loading, setLoading] = React.useState(false),
    [form] = Form.useForm(),
    [ratioTableData, setRatioTableData] = React.useState<any>([]),
    [isEditor] = React.useState<any>(false),
    [referenceYearOptions, setReferenceYearOptions] = React.useState(); //参考年份列表

  const onUnitChange = async () => {
    const temp = YearOptions(moment(year).format('YYYY'));
    setReferenceYearOptions(temp);
    form.setFieldsValue({ referenceYear: [temp[0].value] });
    //首次加载
    if (isFirst) {
      isFirst = false;
      form.submit();
    }
  };

  React.useEffect(() => {
    if (selectData?.unitId) {
      isFirst = true;
      onUnitChange();
    }
  }, []);
  //月份数据加总
  const monthToYear = (val: any) => {
    if (!val?.length) return '0';
    else
      return val.some((t: any) => t !== null)
        ? parseFloat(val.reduce((a: number, b: number) => a + b)).toFixed(3)
        : null;
  };
  //处理表格数据
  const getNewTableData = (data: any) => {
    //月计划
    const radio: any = [];
    //月度分解比例
    Object.entries(data).forEach((item: any) => {
      let _temp: any = [];
      Object.entries(item[1].proportion).forEach((_t: any) => {
        Object.entries(_t[1]).forEach((x: any) => {
          let count: any = '',
            title = '';
          const month: any = {};
          if (x[0].includes('plan')) {
            title = _t[0] + '年计划比例';
          }
          if (x[0].includes('operate')) {
            title = _t[0] + '年经营比例';
          }
          if (x[0].includes('guoneng')) {
            title = _t[0] + '年国能日新预测比例';
          }
          if (x[0].includes('huineng')) {
            title = _t[0] + '年金风慧能预测比例';
          }
          if (x[0].includes('settlement')) {
            title = _t[0] + '年结算比例';
          }
          count = monthToYear(x[1]);
          x[1]?.forEach((y: any, i: number) => {
            month[OPTION_KEY[i + 1]] = y !== null ? parseFloat((y * 100) as any).toFixed(2) : y;
          });
          if (count !== null) {
            _temp.push({
              title,
              count: count,
              ...month,
            });
          }
        });
      });
      const str = moment(form.getFieldValue('date')).format('YYYY') + '年计划比例';
      const top = _temp.filter((t: any) => t.title === str);
      // setValueData(_temp)//设置比例数据
      if (top.length) {
        _temp = _temp
          .map((t: any) => {
            if (t.title === str) {
              t.editor = 1;
            }
            return t;
          })
          .sort((a: any, b: any) => {
            return a.title === str ? -1 : b.title.substring(0, 4) - a.title.substring(0, 4);
          });
      } else {
        _temp.unshift({
          title: str,
          January: '0',
          February: '0',
          March: '0',
          April: '0',
          May: '0',
          June: '0',
          July: '0',
          August: '0',
          September: '0',
          October: '0',
          November: '0',
          December: '0',
          editor: 1,
        });
      }
      radio.push(_temp);
    });
    return radio;
  };
  const _onFinish = useDebounceFn(
    async (values: any) => {
      setLoading(true);
      setRatioTableData([]);
      const _formData: any = values,
        _date = moment(_formData.date).format('YYYY'),
        _referenceYear = _formData.referenceYear || [],
        _unit = _formData.unit;
      const referenceYearParams = _referenceYear.map((t: any) => {
        return {
          dataTypeList: ['settlement', 'operate', 'huineng', 'guoneng', 'plan'],
          year: t,
        };
      });
      const param: any = {
        reqDataScopes: [
          {
            dataTypeList: ['settlement', 'operate', 'huineng', 'guoneng', 'plan'],
            year: _date,
          },
          ...referenceYearParams,
        ],
        respDataTypes: ['numerical', 'proportion'],
        stationIds: [_unit],
      };

      //通过stationId去查找marketId
      const result = stations.find((item: any) => item.stationId === values.unit);
      let _marketId = '';
      if (result) {
        _marketId = result.marketId;
      }

      if (useNewServers.includes(_marketId)) {
        param.marketId = _marketId;
      }

      const res = await querypowerGenerationData(param, _marketId).catch();
      if (res?.statusCode === HttpCode.SUCCESS) {
        //处理表格数据
        const data = getNewTableData(res.data || {});
        setRatioTableData(data[0] || []);
      }
      setLoading(false);
    },
    { wait: 500 },
  );

  const initialValues = () => {
    return {
      unit: selectData?.unitId,
    };
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <Form
          form={form}
          initialValues={initialValues()}
          className={styles.formStyles}
          onFinish={_onFinish.run}
        >
          <Form.Item
            name="unit"
            className={styles.cell_item}
            rules={[{ required: true, message: '请选择交易单元' }]}
          >
            <Select
              style={{ width: 240 }}
              placeholder="选择交易单元"
              showSearch
              options={stations.map((t: any) => ({ label: t.label, value: t.value }))}
              onChange={() => {
                onUnitChange();
              }}
              filterOption={(input, option) => {
                return (option?.label as unknown as string)
                  .toLowerCase()
                  .includes(input.toLowerCase());
              }}
            />
          </Form.Item>
          <Form.Item name="referenceYear" className={styles.cell_item}>
            <MySelect options={referenceYearOptions} />
          </Form.Item>
          <Button className={styles.submit} type="primary" htmlType="submit">
            查询
          </Button>
        </Form>
      </div>
      {loading ? (
        <PageLoading />
      ) : (
        <div className={styles.content}>
          {ratioTableData?.length ? (
            <MonthRatioTable
              setTableData={setRatioTableData}
              tableData={ratioTableData}
              tableHeader={tableHead_3}
              editor={isEditor}
              style={{ maxHeight: 'calc(100vh - 158px)' }}
            />
          ) : (
            <TRDefault type="emptysm" />
          )}
        </div>
      )}
    </div>
  );
};

export default MonthRatio;
